package xsource

import (
	"encoding/json"
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xlog"
	"gitee.com/xiaoyutab/xgotool/xerror"
	"gitee.com/xiaoyutab/xgotool/xgodb"
)

// 队列监听，用于同步插入查询结果
//
//	xsource.find	<SourceLog>
func NsqRun(param []byte) error {
	pm := SourceLog{}
	if err := json.Unmarshal(param, &pm); err != nil {
		return err
	}
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	if pm.SourceChildId == 0 {
		return xlog.NN("溯源模块产品日志中，未关联查询产品")
	}
	if pm.Ip == 0 {
		pm.Ip = xgodb.KvId("127.0.0.1")
	}
	if pm.CreatedAt == "" {
		pm.CreatedAt = time.Now().Format(time.DateTime)
	}
	err := _default.DB.Save(&pm).Error
	if err != nil {
		return xlog.EE("溯源模块产品日志插入失败", err)
	}
	return nil
}
